package pilgun.Multithread.OrderedThreads;

import java.util.Random;

class MyThread extends Thread {
	private int num; 
	private static OrderedThreads lockObj;
	
	
	public MyThread (int num, OrderedThreads o) {
		super();
		this.num = num;
		lockObj = o;
	}
	public void run(){
		for(;;){
			lockObj.check(num);
		}
	}
}



public class OrderedThreads{
	
	private static final int M = 5;
	private static int current = 1;
	private Random rand = new Random();
	
	synchronized void check(int num) {
		while (num != current){
			System.out.println("Thread "+  num + " waiting ");
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println(num);
		current = (current) % (M) + 1;
		try {
			Thread.sleep(rand.nextInt(2000));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		notifyAll();
	}
	
	public static void main(String[] args) {
		OrderedThreads lockObj = new OrderedThreads();
		for (int i=1; i <= M; i++){
			new MyThread(i, lockObj).start();
		}
	}
	
}
